package org.duiduo.util;

import org.slf4j.MDC;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Callable;

/**
 * 线程MDC工具类
 *
 * @author liangze
 * @date 2022/5/19 21:59
 */
public class ThreadMDCUtil {

    public static final String TRACE_ID = "trace_id";
    public static final String TRACE_ID_2 = "traceId";

    /**
     * 创建traceId
     *
     * @return traceId
     */
    private static String createTraceId() {
        return UUID.randomUUID().toString().replace("-", "").toUpperCase();
    }

    /**
     * 设置traceId
     */
    public static void setTraceId(String traceId) {
        MDC.put(TRACE_ID, traceId);
    }

    /**
     * 设置traceId，如果已经存在则不设置
     */
    public static void setTraceIdIfAbsent() {
        if (MDC.get(TRACE_ID) == null) {
            MDC.put(TRACE_ID, createTraceId());
        }
    }

    /**
     * 获取traceId
     *
     * @return traceId
     */
    public static String getTraceId() {
        return MDC.get(TRACE_ID);
    }

    public static <T> Callable<T> wrap(final Callable<T> callable, final Map<String, String> context) {
        return () -> {
            if (context == null) {
                MDC.clear();
            } else {
                MDC.setContextMap(context);
            }
            setTraceIdIfAbsent();
            try {
                return callable.call();
            } finally {
                MDC.clear();
            }
        };
    }

    public static Runnable wrap(final Runnable runnable, final Map<String, String> context) {
        return () -> {
            if (context == null) {
                MDC.clear();
            } else {
                MDC.setContextMap(context);
            }
            setTraceIdIfAbsent();
            try {
                runnable.run();
            } finally {
                MDC.clear();
            }
        };
    }
}
